package com.juzhencms.apps.busi.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.AdminMenuService;
import com.juzhencms.apps.busi.service.SiteService;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.common.interceptor.UserInterceptor;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;


@Controller
@Slf4j
public class MainController  extends BaseController{
	
	
	@Autowired
	private AdminMenuService adminMenuService;
	
	@Autowired
	private UserService userService;

	@Autowired
	SiteService siteService;
	
	
	
	@RequestMapping(value="/",method = RequestMethod.GET,produces="application/json; charset=UTF-8")
	@ResponseBody
    public Map index(){
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
		Date date = new Date();
		Map result=new HashMap();
		result.put("appid", this.getCommonService().getConfig().getValue("app.appid"));
		result.put("time", sdf.format(date));
		result.put("clientIp", this.getRequest().getRemoteAddr());
		return result;
    }
	
	//获取随机数
	@RequestMapping(value="/makeEncodingAESKey",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String makeEncodingAESKey(HttpServletRequest request){
		Map data=new HashMap();		
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		//log.info(str.length()+"====str.length");
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
		for(int i=0;i<43;i++) {
			//26+26+10=62
			int number = random.nextInt(62);// [0,51)
	        sb.append(str.charAt(number));
		}
		String EncodingAESKey= sb.toString();
		data.put("data", EncodingAESKey);
		
		return WebUtil.resultString(data,request);
	}
	
	
	
	
	
	@RequestMapping(value="/userInfo",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String userInfo(HttpServletRequest request){
			
		
		
		AdminLoginUser user=this.getLoginUser();
		
		
		
		
		
		if(user==null || user.getId()==0){
			Map result=new HashMap();
			result.put("result",-1);
			result.put("msg", "请先登录");
			
			return WebUtil.resultString(result,request);
		}
		
		//根据角色获取权限
		//Map userData=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where id=?", new Object[]{user.get("id")});
		
		
		
		
		//---------------------
		
		//生成菜单
		Map userMenu=user.getUserMenu();
		//Map userPermissions=user.getPermissions();
		
		//用户信息
		Map userInfo=new HashMap();
		userInfo.put("id", user.getId());
		userInfo.put("user", user.getUser());
		userInfo.put("name", user.getName());
		//userInfo.put("token", user.get("token"));//采用cookie，应该不再需要回传token了
		userInfo.put("img", user.getImg());
		userInfo.put("org_id", user.getOrgId());
		userInfo.put("org_name", user.getOrgName());
		userInfo.put("token", user.getToken());
		
		Map result=new HashMap();
		result.put("result",1);
		result.put("moduleMenu",userMenu);
		result.put("user",userInfo);
		result.put("fileUrlPath",this.getCommonService().getConfig().getUploadUrlPath());
		result.put("profilesActive",this.getCommonService().getConfig().getValue("spring.profiles.active"));
		result.put("weixinAccount",Config.getValue("weixin.account"));
		
		return WebUtil.resultString(result,request);
		
		
	}
	
	/**
	 * 清空缓存中的用户信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/refreshLoginUser",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String refreshLoginUser(HttpServletRequest request){
			
		
		//清空用户缓存
		AdminLoginUser user=this.getLoginUser();
		String accessTokenId=user.getAccessTokenId();
		String cacheKey=UserService.cacheKeyPrefix+accessTokenId;
		this.getCommonService().getCacheSource().getDBCache().evict(cacheKey);
		
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
		
		
	}
	
	
	@RequestMapping(value="/welcomeInfo",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String welcomeInfo(HttpServletRequest request){
			


		Map result=new HashMap();
		result.put("result",1);
		
		Map countNum=new HashMap();
		
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
		
		Date date=new Date();
		String todayStr = formatter.format(date);
		
		//根据当前登录用户站点判断 index页数据统计信息  modify by sty  20190715
		String siteIds = this.getLoginUser().getSiteIds();
		
		
		//公众号数量
		int siteCount=0;
		if(siteIds!=null && !siteIds.equals("0")) {
			siteCount=siteIds.split(",").length;
		}
		countNum.put("siteCount", siteCount);
		
		String where =" where site_id in ("+siteIds+") ";
		
		
		
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			where+=" and site_id =  "+Integer.parseInt(request.getParameter("site_id").trim())+" ";
		}
		
		//资讯总数
		int totalNewsCount=0;
		Map tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.news+" where del_flag=0 and (share=1 or org_id in("+this.getLoginUser().getSubOrgIds()+"))");
		if(tmp!=null){
			totalNewsCount=new Integer(tmp.get("count_num").toString());
			countNum.put("totalNewsCount", totalNewsCount);
		}
		
		//素材总数
		int totalResourceCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.appResource+" where del_flag=0 and (share=1 or org_id in("+this.getLoginUser().getSubOrgIds()+"))");
		if(tmp!=null){
			totalResourceCount=new Integer(tmp.get("count_num").toString());
			countNum.put("totalResourceCount", totalResourceCount);
		}	
		
		/*//当天推送消息数
		int todayMessageCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.appMessage+" "+where+" and send_time>=? and send_time<=? and status=1 and del_flag=0",new Object[]{todayStr+" 00:00:00",todayStr+" 23:59:59"});
		if(tmp!=null){
			todayMessageCount=new Integer(tmp.get("count_num").toString());
			countNum.put("todayMessageCount", todayMessageCount);
		}*/
		
		//待审批内容数
		int todayMessageCount=0;
		String checkWhere=" where del_flag=0 and check_status=0 ";
		if(this.getLoginUser().getRoleIdList()!=null && this.getLoginUser().getRoleIdList().size()>0) {
			String myRoleIds=org.apache.commons.lang3.StringUtils.join(this.getLoginUser().getRoleIdList().toArray(),",");
			checkWhere+=" and check_role_id in ("+myRoleIds+") ";
		}else {
			checkWhere+=" and 0 ";
		}
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.checkRecord+checkWhere);
		if(tmp!=null){
			todayMessageCount=new Integer(tmp.get("count_num").toString());
			countNum.put("todayMessageCount", todayMessageCount);
		}
		
		
		/*//当天资讯数
		int todayNewsCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.news+" "+where+" and create_time>=? and del_flag=0",new Object[]{todayStr+" 00:00:00"});
		if(tmp!=null){
			todayNewsCount=new Integer(tmp.get("count_num").toString());
			countNum.put("todayNewsCount", todayNewsCount);
		}
			
		
		
		//今日访问用户数
		int todayVistorCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(distinct session_id) as count_num from "+DBTable.log+" "+where+" and log_date=?",new Object[]{todayStr});
		if(tmp!=null){
			todayVistorCount=new Integer(tmp.get("count_num").toString());
			countNum.put("todayVistorCount", todayVistorCount);
		}
			
		
		//今日点击量
		int todayHitCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.log+" "+where+" and log_date=?",new Object[]{todayStr});
		if(tmp!=null){
			todayHitCount=new Integer(tmp.get("count_num").toString());
			countNum.put("todayHitCount", todayHitCount);
		}*/
		
		result.put("countNum", countNum);
		
		//最近10天的点击量
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(date); 
		cal.add(cal.DATE, -10);
		List countList=this.getCommonService().getJdbcDao().querySql("select count(id) as visit_num,DATE_FORMAT(create_time,'%Y-%m-%d') as log_date from "+DBTable.news+" where create_time>=? and del_flag=0 and (share=1 or org_id in("+this.getLoginUser().getSubOrgIds()+")) group by log_date order by log_date asc", new Object[]{formatter.format(cal.getTime())});
		
		List dateList=new ArrayList();
		while(cal.getTime().before(date) || cal.getTime().equals(date)){
			dateList.add(formatter.format(cal.getTime()));
			cal.add(cal.DATE, 1);
		}
		
		//y轴最大值
		int max_num=10;
		//Y轴刻度的间隔值
		int tickInterval=1;
		
		List logList=new ArrayList();
		for(int i=0;i<dateList.size();i++){
			String tmpDate=dateList.get(i).toString();
			int tmpNum=0;
			if(countList!=null)
				for(int j=0;j<countList.size();j++){
					Map tmpRow=(Map)countList.get(j);
					if(tmpDate.equals(tmpRow.get("log_date").toString())){
						tmpNum=new Integer(tmpRow.get("visit_num").toString());
					}
				}
			logList.add(tmpNum);
			if(tmpNum>max_num){
				max_num=tmpNum;
			}
				
		}
		
		
		if(max_num>100){
			//计算获得y轴最大坐标
			int tmplength=(max_num+"").length();
			int firstnum=new Integer((max_num+"").substring(0, 1));

			if(firstnum<5)
				firstnum=5;
			else
				firstnum=10;
				
			max_num=firstnum;
			for(int i=1;i<tmplength;i++){
				max_num=max_num*10;
			}
			//获取Y轴刻度的间隔值
			tickInterval=max_num/firstnum;
		}
		
		
		
		Map countResult=new HashMap();
		countResult.put("data", logList);
		countResult.put("categories", dateList);
		countResult.put("max_num", max_num);
		countResult.put("tickInterval", tickInterval);
		result.put("visitLogs", countResult);
		
		
		return WebUtil.resultString(result,request);
		
		
	}
	
	@SuppressWarnings("all")
	@RequestMapping(value="/countInfo",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String countInfo(HttpServletRequest request) throws ParseException{
		
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
		
		Date beginDate=formatter.parse(request.getParameter("beginDate"));
		Date endDate=formatter.parse(request.getParameter("endDate"));
		
		
		Map result=new HashMap();
		result.put("result",1);
		
		Map countNum=new HashMap();
		
		countNum.put("beginDate", formatter.format(beginDate));
		countNum.put("endDate", formatter.format(endDate));
		
		//根据当前登录用户站点判断 index页数据统计信息  modify by sty  20190715
		String siteIds = this.getLoginUser().getSiteIds();
		String where =" where site_id in ("+siteIds+") ";
		
		//根据当前登录用户站点判断 index页数据统计信息  modify by sty  20190715
		where+="and log_date>='"+request.getParameter("beginDate")+"' and log_date<='"+request.getParameter("endDate")+"' ";

		if(request.getParameter("siteId")!=null && !request.getParameter("siteId").equals("")) {
			int siteId=Integer.parseInt(request.getParameter("siteId"));
			where+=" and site_id="+siteId+" ";
		}
		
		
		
		//访问用户数
		int todayVistorCount=0;
		Map tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(distinct session_id) as count_num from "+DBTable.log+" "+where+" ",new Object[]{});
		if(tmp!=null){
			todayVistorCount=new Integer(tmp.get("count_num").toString());
			countNum.put("vistorCount", todayVistorCount);
		}

		//点击量
		int todayHitCount=0;
		tmp=(Map)this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.log+" "+where+" ",new Object[]{});
		if(tmp!=null){
			todayHitCount=new Integer(tmp.get("count_num").toString());
			countNum.put("hitCount", todayHitCount);
		}
		
		result.put("countNum", countNum);
		
		//查询PV
		if(true) {
			//最近10天的点击量
			Calendar cal = Calendar.getInstance(); 
			cal.setTime(beginDate); 

			List countList=this.getCommonService().getJdbcDao().querySql("select count(id) as visit_num,log_date from "+DBTable.log+" "+where+" group by log_date order by log_date asc", new Object[]{});
			
			List dateList=new ArrayList();
			while(cal.getTime().before(endDate) || cal.getTime().equals(endDate)){
				dateList.add(formatter.format(cal.getTime()));
				cal.add(cal.DATE, 1);
			}
			
			//y轴最大值
			int max_num=100;
			//Y轴刻度的间隔值
			int tickInterval=10;
			
			List logList=new ArrayList();
			for(int i=0;i<dateList.size();i++){
				String tmpDate=dateList.get(i).toString();
				int tmpNum=0;
				if(countList!=null)
					for(int j=0;j<countList.size();j++){
						Map tmpRow=(Map)countList.get(j);
						if(tmpDate.equals(tmpRow.get("log_date").toString())){
							tmpNum=new Integer(tmpRow.get("visit_num").toString());
						}
					}
				logList.add(tmpNum);
				if(tmpNum>max_num){
					max_num=tmpNum;
				}
					
			}
			
			
			if(max_num>100){
				//计算获得y轴最大坐标
				int tmplength=(max_num+"").length();
				int firstnum=new Integer((max_num+"").substring(0, 1));

				if(firstnum<5)
					firstnum=5;
				else
					firstnum=10;
					
				max_num=firstnum;
				for(int i=1;i<tmplength;i++){
					max_num=max_num*10;
				}
				//获取Y轴刻度的间隔值
				tickInterval=max_num/firstnum;
			}
			
			
			
			Map countResult=new HashMap();
			countResult.put("data", logList);
			countResult.put("categories", dateList);
			countResult.put("max_num", max_num);
			countResult.put("tickInterval", tickInterval);
			result.put("pvData", countResult);
		}
		
		//查询UV
		if(true) {
			//最近10天的点击量
			Calendar cal = Calendar.getInstance(); 
			cal.setTime(beginDate); 

			List countList=this.getCommonService().getJdbcDao().querySql("select count(distinct session_id) as visit_num,log_date from "+DBTable.log+" "+where+" group by log_date order by log_date asc", new Object[]{});
			
			List dateList=new ArrayList();
			while(cal.getTime().before(endDate) || cal.getTime().equals(endDate)){
				dateList.add(formatter.format(cal.getTime()));
				cal.add(cal.DATE, 1);
			}
			
			//y轴最大值
			int max_num=100;
			//Y轴刻度的间隔值
			int tickInterval=10;
			
			List logList=new ArrayList();
			for(int i=0;i<dateList.size();i++){
				String tmpDate=dateList.get(i).toString();
				int tmpNum=0;
				if(countList!=null)
					for(int j=0;j<countList.size();j++){
						Map tmpRow=(Map)countList.get(j);
						if(tmpDate.equals(tmpRow.get("log_date").toString())){
							tmpNum=new Integer(tmpRow.get("visit_num").toString());
						}
					}
				logList.add(tmpNum);
				if(tmpNum>max_num){
					max_num=tmpNum;
				}
					
			}
			
			
			if(max_num>100){
				//计算获得y轴最大坐标
				int tmplength=(max_num+"").length();
				int firstnum=new Integer((max_num+"").substring(0, 1));

				if(firstnum<5)
					firstnum=5;
				else
					firstnum=10;
					
				max_num=firstnum;
				for(int i=1;i<tmplength;i++){
					max_num=max_num*10;
				}
				//获取Y轴刻度的间隔值
				tickInterval=max_num/firstnum;
			}
			
			
			
			Map countResult=new HashMap();
			countResult.put("data", logList);
			countResult.put("categories", dateList);
			countResult.put("max_num", max_num);
			countResult.put("tickInterval", tickInterval);
			result.put("uvData", countResult);
		}
		
		//查询操作系统
		if(true) {
			List tmpList=this.getCommonService().getJdbcDao().querySql("select count(distinct session_id) as visit_num,client_system from "+DBTable.log+" "+where+" and client_system!='UNKNOWN' group by client_system order by visit_num desc limit 0,10", new Object[]{});
			List countList=new ArrayList();
			if(tmpList!=null) {
				for(int i=0;i<tmpList.size();i++) {
					Map row=(Map)tmpList.get(i);
					List subList=new ArrayList();
					subList.add(row.get("client_system"));
					subList.add(row.get("visit_num"));
					countList.add(subList);
				}
			}
			
			result.put("osData", countList);		
		}
		
		//查询浏览器
		if(true) {
			List tmpList=this.getCommonService().getJdbcDao().querySql("select client_browser,count(distinct session_id) as visit_num from "+DBTable.log+" "+where+" and client_browser!='UNKNOWN' and client_browser!='BOT' group by client_browser order by visit_num desc limit 0,10", new Object[]{});
			List countList=new ArrayList();
			if(tmpList!=null) {
				for(int i=0;i<tmpList.size();i++) {
					Map row=(Map)tmpList.get(i);
					List subList=new ArrayList();
					subList.add(row.get("client_browser"));
					subList.add(row.get("visit_num"));
					countList.add(subList);
				}
			}
			result.put("browserData", countList);
		}
		
		//查询url及点击量
		if(true) {
			List countList=this.getCommonService().getJdbcDao().querySql("select count(id) as visit_num,concat('http://',domain,url) as urlstr from "+DBTable.log+" "+where+" group by url,domain order by visit_num desc limit 0,10", new Object[]{});
			result.put("urlData", countList);
		}
		
		
		
		
		return WebUtil.resultString(result,request);
		
		
	}
	
	@RequestMapping(value="/configVarsJs",produces="text/html; charset=UTF-8")
	@ResponseBody
	@Cacheable(value="dbCache",key="#root.targetClass+'.'+#root.methodName")
	public String configVarsJs(HttpServletRequest request){
		
		
		/*Map user=(Map)this.getLoginUser();
		
		if(user==null || user.get("id")==null){
			Map result=new HashMap();
			result.put("result",-1);
			result.put("msg", "请先登录");
			
			return WebUtil.resultString(result,request);
		}*/
		Map dictonaryData=new HashMap();
		//读取数据字典
		List dictonaryList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.dictionary);
		if(dictonaryList!=null) {
			for(int i=0;i<dictonaryList.size();i++) {
				Map tmp=(Map)dictonaryList.get(i);
				
				
				List items=this.getCommonService().getJdbcDao().querySql("select value as id,text from "+DBTable.dictionaryItem+" where dictionary_id=? and publish=1 and del_flag=0 order by position asc,id asc", new Object[] {tmp.get("id")});
				if(tmp.get("data_type").toString().equals("1") && items!=null) {
					for(int j=0;j<items.size();j++) {
						Map item=(Map)items.get(j);
						item.put("id", new Integer(item.get("id").toString()));
					}
				}
				
				
				dictonaryData.put(tmp.get("name"), items);
			}
		}
		
		
		String jsonResult = JSON.toJSONStringWithDateFormat(dictonaryData, JSON.DEFFAULT_DATE_FORMAT);
		
		return "var enumVars="+jsonResult;
	}
	
	
	
}
